package cn.mrlong.cleardatamanager;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ClearDataManager {
    private static String TAG = "ClearDataManager ===>";

    /**
     * 应用程序运行命令获取 Root权限，设备必须已破解(获得ROOT权限)
     *
     * @return 应用程序是/否获取Root权限
     */
    public static boolean upgradeRootPermission(String pkgCodePath) {
        Process process = null;
        DataOutputStream os = null;
        try {
            String cmd = "chmod 777 " + pkgCodePath;
            process = Runtime.getRuntime().exec("su"); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        return true;
    }

    /**
     * 获取系统安装的应用，并区分系统与非系统
     */
    public static void getAppList(Context context) {
        PackageManager pm = context.getPackageManager();
        // Return a List of all packages that are installed on the device.
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo packageInfo : packages) {
            // 判断系统/非系统应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) // 非系统应用
            {
                Log.e(TAG, "非系统应用 packageInfo=" + packageInfo.packageName);
//                if (packageInfo.packageName.equals("com.mediatek.mobileportal")) {
                    Log.e(TAG, "名字 " +pm.getApplicationLabel(packageInfo.applicationInfo));
                    boolean flag = removeAppData(packageInfo.packageName);
                    if (flag) {
                        Log.e(TAG, "清楚成功");
                    } else {
                        Log.e(TAG, "清楚失败");
                    }
//                }
                //System.out.println("MainActivity.getAppList, packageInfo=" + packageInfo.packageName);
            } else {
//                // 系统应用
//                if (packageInfo.packageName.equals("com.rdafm.fmtx")) {
//                    Log.e(TAG, "系统应用 packageInfo=" + packageInfo.packageName);
//                    boolean flag = removeAppData(packageInfo.packageName);
//                    if (flag) {
//                        Log.e(TAG, "清楚成功");
//                    } else {
//                        Log.e(TAG, "清楚失败");
//                    }
//                }
            }
        }
    }
    /**
     *根据包名清除用户数据【需要root权限】
     */
    public static boolean removeAppData(String packageName) {
        File file = new File("/data/data/" + packageName);
        System.out.println("包名为：" + packageName);
        if (file.exists()) {
            DataOutputStream os = null;
            DataInputStream is = null;
            DataInputStream es = null;
            BufferedReader buf = null;
            Process p = null;
            try {
                p = Runtime.getRuntime().exec("su");// 获得root权限
                os = new DataOutputStream(p.getOutputStream());
                // is = new DataInputStream( p.getInputStream( ) );
                buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
                es = new DataInputStream(p.getErrorStream());
                os.writeBytes("ls /data/data/" + packageName + "/ \n");
                os.flush();
                List<String> list = new ArrayList<String>();
                list.add("cache");
                list.add("databases");
                list.add("files");
                list.add("shared_prefs");
                for (int i = 0; i < list.size(); i++) {
                    os.writeBytes("rm -f -r /data/data/" + packageName + "/" + (String) list.get(i) + " \n");// 删除文件和文件夹
                    //System.out.println("遍历 " + (String) list.get(i));
                    Log.e(TAG, "遍历" + (String) list.get(i));
                    os.flush();
                }
                os.flush();
                os.writeBytes("exit\n");
                os.flush();
                os.close();
                p.destroy();

            } catch (IOException e) {
                try {
                    if (null != os)
                        os.close();
                    if (null != is)
                        is.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                if (null != p)
                    p.destroy();
            }
            return true;
        } else {
            return false;
        }
    }

    public static void de() {
        try {
//            p = Runtime.getRuntime( ).exec( "su" );
//            os = new DataOutputStream( p.getOutputStream( ) );
//            is = new DataInputStream( p.getInputStream( ) );
//            os.writeBytes( "pm clear " + packageName + " \n" );
//            os.flush( );
//            os.writeBytes( "echo test  \n" );// 回显test 并获得test，确保上面的代码已经执行
//            os.flush( );
//            String result = is.readLine( );
//            os.writeBytes( "exit\n" );
//            os.flush( );
//            os.close( );
//            p.destroy( );
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
